// https://blog.csdn.net/mengxiangxingdong/article/details/99237204
// https://zhaoqize.github.io/puppeteer-api-zh_CN/#/
// https://www.cnblogs.com/wuweiblogs/p/12918968.html

//模拟百度搜索，获取带有广告位的搜索记录
var autoSearch = async (page, keywords) => {

    await page.emulate({
        name: 'iPhone X',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 400,
            height: 812,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    })
    await page.setJavaScriptEnabled(true);

    //结果
    var resultArray = [];

    if (keywords && keywords.length) {

        await page.addScriptTag({url: 'http://cdn.bootcss.com/jquery/3.2.0/jquery.min.js'})

        //循环查询
        for (var i = 0; i < keywords.length; i++) {
            let item = keywords[i];
            if (!item) continue;

            console.log('--------------------------------------------------------------------')
            console.log("开始搜索关键字：" + item)
            console.log("进入百度首页")
            await page.goto('https://www.baidu.com/');

            console.log("模拟搜索点击")
            await page.waitForSelector('input#index-kw')
            await page.type("input#index-kw", item, {delay: 20}) //输入关键字

            //键盘按回车
            await page.waitFor(100);
            await page.keyboard.press('Enter');

            // await page.waitForSelector('#index-bn[type="submit"]')
            // await page.click('#index-bn[type="submit"]') //点击搜索 [百度好像无法调用点击事件]

            console.log("等待选项卡跳转")
            await page.waitForNavigation(10000); //等待选项卡跳转

            await page.waitForSelector('#results')
            console.log("#result 加载成功")

            await page.waitFor(500); //等待jquery加载成功

            console.log("开始收集【广告】数据")
            const kwresult = await page.evaluate((keyword) => {
                let data = []; // 初始化空数组来存储数据
                $('.ec_ad_results>div').each(function (i, dom) {
                    let $dom = $(dom)
                    let title = $dom.find('a').eq(0).text();
                    let desc = $dom.find('p').eq(0).text();
                    let url = $dom.find('.ec-tuiguang').siblings('a').eq(0).text()
                    //只查找前4个
                    if (data.length < 4) {
                        data.push({
                            "关键字": $('#kw').val(),
                            "网址": url,
                            "标题": title,
                            "描述": desc
                        })
                    }
                })
                if (data.length === 0) {
                    data.push({keyword, url: "无", title: "", desc: "",})
                }
                console.log("page.log 搜索结果：" + JSON.stringify(data))
                return data;
            }, item);

            console.log("搜索完成：关键字：" + item + "，搜索结果：" + JSON.stringify(kwresult))
            resultArray.push(...kwresult);
            await page.waitFor(100)

            // await page.waitForNavigation({timeout: 200000000})  //等待网页操作
        }
        console.log("baiduMobileSearch 搜索结果：\n" + JSON.stringify(resultArray))

    } else {
        console.log("进入百度首页")
        await page.goto('https://www.baidu.com/');
        await page.waitForSelector('input#index-kw')
    }

    return resultArray;
}

export default autoSearch
